/**
 * Notes: 充值订单数据模型 - 宠物门店预约小程序
 * Date: 2025-01-27
 */

const BaseModel = require('./base_model.js');
const timeUtil = require('../../framework/utils/time_util.js');

class RechargeModel extends BaseModel {

	/**
	 * 充值订单状态
	 */
	static STATUS = {
		PENDING_PAY: 101,    // 待支付
		PAID: 201,           // 已支付
		CANCELLED: 301,      // 已取消
		FAILED: 401          // 支付失败
	};

	/**
	 * 充值订单状态描述
	 */
	static STATUS_DESC = {
		[RechargeModel.STATUS.PENDING_PAY]: '待支付',
		[RechargeModel.STATUS.PAID]: '已支付',
		[RechargeModel.STATUS.CANCELLED]: '已取消',
		[RechargeModel.STATUS.FAILED]: '支付失败'
	};

	constructor() {
		super();
		this._name = 'ax_recharge_orders';
	}

	/**
	 * 生成充值订单号
	 * @returns {string} 充值订单号
	 */
	static generateOrderNumber() {
		const now = new Date();
		const year = now.getFullYear();
		const month = String(now.getMonth() + 1).padStart(2, '0');
		const day = String(now.getDate()).padStart(2, '0');
		const random = Math.random().toString(36).substr(2, 6).toUpperCase();
		return `RCH${year}${month}${day}${random}`;
	}

	/**
	 * 创建充值订单
	 * @param {Object} data 充值订单数据
	 * @returns {Object} 创建结果
	 */
	async createOrder(data) {
		const orderData = {
			orderNumber: RechargeModel.generateOrderNumber(),
			userId: data.userId,
			amount: data.amount,           // 充值金额（分）
			bonus: data.bonus || 0,        // 赠送金额（分）
			totalAmount: data.amount + (data.bonus || 0), // 总到账金额（分）
			packageId: data.packageId || '',
			status: RechargeModel.STATUS.PENDING_PAY,
			payTime: 0,
			transactionId: '',
			createTime: timeUtil.time(),
			updateTime: timeUtil.time()
		};

		return await RechargeModel.insert(orderData);
	}

	/**
	 * 更新充值订单状态
	 * @param {string} orderId 订单ID
	 * @param {number} status 新状态
	 * @param {Object} extraData 额外数据
	 * @returns {Object} 更新结果
	 */
	async updateStatus(orderId, status, extraData = {}) {
		const updateData = {
			status: status,
			updateTime: timeUtil.time(),
			...extraData
		};

		return await RechargeModel.edit({ _id: orderId }, updateData);
	}

	/**
	 * 获取用户充值订单列表
	 * @param {string} userId 用户ID
	 * @param {number} page 页码
	 * @param {number} size 每页数量
	 * @returns {Object} 订单列表
	 */
	async getUserOrders(userId, page = 1, size = 20) {
		const where = { userId: userId };
		const orderBy = { createTime: 'desc' };
		
		return await RechargeModel.getList(where, '*', orderBy, page, size, true, 0);
	}

	/**
	 * 获取充值订单详情
	 * @param {string} orderId 订单ID
	 * @param {string} userId 用户ID（可选，用于权限验证）
	 * @returns {Object} 订单详情
	 */
	async getOrderDetail(orderId, userId = null) {
		const where = { _id: orderId };
		if (userId) {
			where.userId = userId;
		}
		
		return await RechargeModel.getOne(where);
	}

	/**
	 * 检查订单是否可以支付
	 * @param {Object} order 订单信息
	 * @returns {boolean} 是否可以支付
	 */
	static canPay(order) {
		return order && order.status === RechargeModel.STATUS.PENDING_PAY;
	}

	/**
	 * 检查订单是否已支付
	 * @param {Object} order 订单信息
	 * @returns {boolean} 是否已支付
	 */
	static isPaid(order) {
		return order && order.status === RechargeModel.STATUS.PAID;
	}

	/**
	 * 获取状态描述
	 * @param {number} status 状态码
	 * @returns {string} 状态描述
	 */
	static getStatusDesc(status) {
		return RechargeModel.STATUS_DESC[status] || '未知状态';
	}

	/**
	 * 检查并取消过期的待支付订单
	 * @param {number} expireMinutes 过期时间（分钟），默认30分钟
	 * @returns {Promise<number>} 取消的订单数量
	 */
	async cancelExpiredOrders(expireMinutes = 30) {
		const expireTime = timeUtil.time() - (expireMinutes * 60);
		
		// 查找过期的待支付订单
		const expiredOrders = await RechargeModel.getAll({
			status: RechargeModel.STATUS.PENDING_PAY,
			createTime: ['<', expireTime]
		});
		
		if (!expiredOrders || expiredOrders.length === 0) {
			return 0;
		}
		
		// 批量更新为已取消状态
		const orderIds = expiredOrders.map(order => order._id);
		await RechargeModel.editBatch(orderIds, {
			status: RechargeModel.STATUS.CANCELLED,
			updateTime: timeUtil.time()
		});
		
		return expiredOrders.length;
	}

	/**
	 * 检查单个订单是否过期并自动取消
	 * @param {string} orderId 订单ID
	 * @param {number} expireMinutes 过期时间（分钟），默认30分钟
	 * @returns {Promise<boolean>} 是否已取消
	 */
	async checkAndCancelExpiredOrder(orderId, expireMinutes = 30) {
		const order = await RechargeModel.getOne({ _id: orderId });
		if (!order) {
			return false;
		}
		
		// 只处理待支付状态的订单
		if (order.status !== RechargeModel.STATUS.PENDING_PAY) {
			return false;
		}
		
		// 检查是否过期
		const expireTime = timeUtil.time() - (expireMinutes * 60);
		if (order.createTime > expireTime) {
			return false;
		}
		
		// 取消过期订单
		await RechargeModel.edit(orderId, {
			status: RechargeModel.STATUS.CANCELLED,
			updateTime: timeUtil.time()
		});
		
		return true;
	}

	/**
	 * 取消用户所有待支付的充值订单
	 * @param {string} userId 用户ID
	 * @returns {number} 取消的订单数量
	 */
	async cancelUserPendingOrders(userId) {
		const where = {
			userId: userId,
			status: RechargeModel.STATUS.PENDING_PAY
		};
		
		// 获取所有待支付订单
		const orders = await RechargeModel.getList(where, '_id');
		if (!orders || !orders.list || orders.list.length === 0) {
			return 0;
		}
		
		// 批量更新为已取消状态
		let cancelCount = 0;
		for (const order of orders.list) {
			await RechargeModel.edit(order._id, {
				status: RechargeModel.STATUS.CANCELLED,
				updateTime: timeUtil.time()
			});
			cancelCount++;
		}
		
		return cancelCount;
	}
}

// 集合名
RechargeModel.CL = "ax_recharge_orders";

// 数据库结构定义
RechargeModel.DB_STRUCTURE = {
	_pid: 'string|true',
	orderNumber: 'string|true|comment=充值订单号',
	userId: 'string|true|comment=用户ID',
	amount: 'int|true|comment=充值金额（分）',
	bonus: 'int|true|default=0|comment=赠送金额（分）',
	totalAmount: 'int|true|comment=总到账金额（分）',
	packageId: 'string|false|default=|comment=充值套餐ID',
	status: 'int|true|default=101|comment=订单状态',
	payTime: 'int|true|default=0|comment=支付时间',
	transactionId: 'string|false|default=|comment=交易ID',
	createTime: 'int|true|comment=创建时间',
	updateTime: 'int|true|comment=更新时间'
};

// 字段前缀
RechargeModel.FIELD_PREFIX = "";

// 禁用自动添加时间和IP字段，使用自定义时间字段
RechargeModel.UPDATE_TIME = false;
RechargeModel.UPDATE_IP = false;
RechargeModel.ADD_ID = false;

module.exports = RechargeModel;